package com.core.controller.test;

import cn.hutool.core.io.FileUtil;

import com.common.enums.ErrorCode;
import com.common.response.BaseResponse;
import com.common.response.ResultUtils;
import com.common.config.CosClientConfig;
import com.common.exception.BusinessException;
import com.core.manager.CosManager;

import java.io.File;
import java.util.Arrays;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author : 帅宏-coding
 * @version : 1.0
 */
@Slf4j
@RestController
public class FileTestController {

  @Resource private CosManager cosManager;

  @Resource private CosClientConfig cosClientConfig;

  @RequestMapping(value = "/fileTest/upload", method = RequestMethod.POST)
  public BaseResponse<String> testUploadFIle(@RequestPart("file") MultipartFile multipartFile) {
    // 先校验文件
    this.validFile(multipartFile);

    String uuid = RandomStringUtils.randomAlphanumeric(8);
    log.info("uuid : {}", uuid);

    String filename = uuid + "-" + multipartFile.getOriginalFilename();
    log.info("filename : {}", filename);

    String filepath = String.format("/%s/%s", "test_file", filename);
    log.info("filepath : {}", filepath);

    File file = null;
    try {
      // 创建临时文件
      String prefix = "temp_" + System.currentTimeMillis() + "_";
      String suffix = "." + FileUtil.getSuffix(multipartFile.getOriginalFilename());
      file = File.createTempFile(prefix, suffix);

      // 将上传的文件传输到临时文件
      multipartFile.transferTo(file);

      // 上传到COS
      cosManager.putObject(filepath, file);

      // 构建访问URL
      String accessUrl =
          String.format(
              "https://%s.cos.%s.myqcloud.com%s",
              cosClientConfig.getBucket(), cosClientConfig.getRegion(), filepath);

      log.info("文件上传成功，访问地址: {}", accessUrl);
      return ResultUtils.success(accessUrl);

    } catch (Exception e) {
      log.error("文件上传失败, filepath = {}", filepath, e);
      throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败: " + e.getMessage());
    } finally {
      // 清理临时文件
      if (file != null && file.exists()) {
        boolean delete = file.delete();
        if (!delete) {
          log.error("临时文件删除失败, filepath = {}", file.getAbsolutePath());
        } else {
          log.info("临时文件已清理: {}", file.getAbsolutePath());
        }
      }
    }
  }

  /** 校验文件 */
  private void validFile(MultipartFile multipartFile) {
    if (multipartFile == null || multipartFile.isEmpty()) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
    }

    // 文件大小
    long fileSize = multipartFile.getSize();
    // 文件后缀
    String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());

    final long ONE_M = 1024 * 1024L;
    if (fileSize > ONE_M) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
    }

    if (fileSuffix == null
        || !Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix.toLowerCase())) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误，只支持jpeg, jpg, svg, png, webp格式");
    }
  }
}
